package com.ch.d0416;

import java.io.*;

public class MsgUtil {

    public static void sendText(String text, OutputStream out) throws IOException {
        DataOutputStream dos = new DataOutputStream(out);
        dos.writeInt(1);
        dos.writeUTF(text);
    }

    public static void sendFile(String filepath,OutputStream out) throws IOException {
        DataOutputStream dos = new DataOutputStream(out);
        dos.writeInt(2);
        File file = new File(filepath);
        //发送文件名
        dos.writeUTF(file.getName());
        byte[] bytes = new byte[1024];
        int count;
        try (FileInputStream fis = new FileInputStream(filepath)){
            while( (count = fis.read(bytes)) > -1) {
                out.write(bytes,0,count);
            }
        }
    }

    public static String recv(InputStream in) throws IOException {
        DataInputStream dis = new DataInputStream(in);
        int i = dis.readInt();
        if (i==1) {
            return recvText(in);
        } else if (i == 2) {
            return recvFile(in);
        }
        return null;
    }

    public static String recvText(InputStream in) throws IOException {
        DataInputStream dis = new DataInputStream(in);
        return dis.readUTF();
    }

    public static String recvFile(InputStream in) throws IOException {
        DataInputStream dis = new DataInputStream(in);
        String filename = dis.readUTF();
        byte[] bytes = new byte[1024];
        int count;
        String filepath = "d:/" + filename;
        try(FileOutputStream fos = new FileOutputStream(filepath)) {
            while((count = in.read(bytes)) > -1) {
                fos.write(bytes,0,count);
            }
        }
        return "接收到文件:" + filename;
    }

}
